package com.ly.websocket.biz;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.ly.websocket.web.WebSocketDo;
import org.springframework.stereotype.Component;

import java.io.IOException;

//@Component
public class DefaultMsgSender implements IMsgSender {

    protected ObjectMapper objectMapper = new ObjectMapper();
    {
        // 解决手动json转换, 日期报错问题
        objectMapper.registerModule(new JavaTimeModule());
    }

    @Override
    public void send(WebSocketDo.Msg msg) throws Exception {
        WebSocketDo.getOnlines().forEach((id,session)->{
            try {
                String json = objectMapper.writeValueAsString(msg);
                session.getBasicRemote().sendText(json);
            } catch (IOException e) {
                throw new RuntimeException("消息发送失败", e);
            }
        });
    }

}
